/**
 * 
 */
package ro.dta.idbi.ui.patterns;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;

import ro.dta.idbi.interfaces.sql.ISqlColumn;
import ro.dta.idbi.interfaces.sql.ISqlConstruct;
import ro.dta.idbi.interfaces.sql.ISqlTable;
import ro.dta.idbi.interfaces.ui.IMainFrame;
import ro.dta.idbi.model.Utils;
import ro.dta.idbi.patterns.TableGenerRev;
import ro.dta.idbi.ui.sql.SqlForeignKeyCell;
import ro.dta.idbi.ui.sql.SqlGraph;
import ro.dta.idbi.ui.sql.SqlTableCell;
import uk.ac.ic.doc.automed.reps.Schema;

import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.swing.mxGraphComponent;

/**
 * UI for the remove total generalisation pattern (reverse of the
 * <i>introduction of total generalisation</i> pattern)
 * 
 * @author Tudor Dobrila
 * 
 */
public class TableGenerRevDialog extends AbstractPatternDialog {

	private static final long serialVersionUID = 127723084447236723L;
	private static final Logger LOGGER = Logger
			.getLogger("ro.dta.idbi.ui.patterns.TableGenerRevDialog");
	
	/**
	 * Check if the current pattern can be applied over a given set of objects
	 * 
	 * Used to check if the items selected by the user in the UI can be used to
	 * apply this transformation pattern over them
	 * 
	 * @param schema
	 *            Schema in the context of which to check the validity of the
	 *            array of objects
	 * @param objects
	 *            Set of objects
	 * @return True if pattern can be applied over set of objects, false
	 *         otherwise
	 */
	public static boolean isValid(final Schema schema, final Object[] objects) {
		if (!TableGenerDialog.isValid(schema, objects)) {
			return false;
		}

		ISqlTable[] tables = new ISqlTable[objects.length];
		System.arraycopy(objects, 0, tables, 0, objects.length);

		// Find parent table
		final ISqlTable parentTbl = Utils.getCommonSupertype(schema, tables);
		if (parentTbl == null) {
			return false;
		}

		// Check if parent table only has cols in PK as columns, so it can be
		// removed
		final List<ISqlColumn> cols = parentTbl.getColumns();
		for (ISqlColumn c : cols) {
			if (!c.isPK()) {
				return false;
			}
		}

		return true;
	}
	
	/**
	 * Parent table
	 */
	private transient ISqlTable parent;

	/**
	 * Remove total generalisation pattern dialog class constructor
	 * 
	 * @param parentFrame
	 *            Parent frame of this dialog
	 * @param schema
	 *            Schema over which the transformation is applied
	 * @param element
	 *            Sql construct(s) over which the transformation is applied
	 * @param beforeLabel
	 *            Label for the before diagram
	 * @param afterLabel
	 *            Label for the transformed diagram
	 */
	public TableGenerRevDialog(final IMainFrame parentFrame, final Schema schema,
			final ISqlConstruct[] element, final JLabel beforeLabel, final JLabel afterLabel) {
		super(parentFrame, schema, element, beforeLabel, afterLabel);

		if (!isValid(schema, element)) {
			throw new IllegalArgumentException(
					"This pattern can't be applied to the given elements");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ro.dta.idbi.ui.patterns.TransformationDialog#createOriginalDiagram()
	 */
	@Override
	protected mxGraphComponent createOriginalDiagram() {
		initialise();
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			SqlTableCell[] newTables = new SqlTableCell[element.length];
			SqlTableCell parentTbl = null;
			for (int i = 0; i < element.length; i++) {
				final SqlTableCell crtTbl = (SqlTableCell) element[i];
				final SqlTableCell newTable = (SqlTableCell) crtTbl.clone();
				final mxGeometry newGeometry = new mxGeometry(i * 170 + 5, 5, element[0]
						.getGeometry().getWidth(), element[0].getGeometry().getHeight());
				newTable.setGeometry(newGeometry);
				newTable.setStyle("SEL_TABLE");
				newTable.layout(graph);
				newTables[i] = newTable;

				if (element[i] == parent) {
					parentTbl = newTable;
				}
			}

			for (int i = 0; i < element.length; i++) {
				if (element[i] != parent) {
					final SqlForeignKeyCell fk = new SqlForeignKeyCell(null, null, "", "", newTables[i],
							parentTbl, "FK_EDGE");
					graph.addCell(fk, graph.getDefaultParent());
				}
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			final mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
			layout.execute(graph.getDefaultParent());
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ro.dta.idbi.ui.patterns.TransformationDialog#createTransformedDiagram()
	 */
	@Override
	protected mxGraphComponent createTransformedDiagram() {
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			for (int i = 0; i < element.length; i++) {
				if (element[i] != parent) {
					final SqlTableCell crtTbl = (SqlTableCell) element[i];
					final SqlTableCell newTable = (SqlTableCell) crtTbl.clone();
					final mxGeometry newGeometry = new mxGeometry(i * 170 + 5, 5, element[0]
							.getGeometry().getWidth(), element[0].getGeometry().getHeight());
					newTable.setGeometry(newGeometry);
					newTable.layout(graph);
				}
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	private void initialise() {
		ISqlTable[] tables = new ISqlTable[element.length];
		System.arraycopy(element, 0, tables, 0, element.length);
		parent = Utils.getCommonSupertype(schema, tables);
		if (parent == null) {
			throw new IllegalArgumentException(
					"This pattern can't be applied to the given elements");

		}

		final StringBuilder cmd = new StringBuilder(TableGenerRev.COMMAND).append(" (");
		cmd.append("<<").append(parent.getValue()).append(">>");
		for (ISqlConstruct e : element) {
			if (e != parent) {
				cmd.append(", <<").append(e.getValue()).append(">>");
			}
		}
		cmd.append(" )");
		macroField.setText(cmd.toString());
	}

}
